package com.wejoy.video.middle.station.data.util;

import com.alibaba.fastjson.JSONObject;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 请求工具类
 */
@Component
public class RequestUtil {
    private final static Logger logger = LoggerFactory.getLogger(RequestUtil.class);
    private static RestTemplate restTemplate;

    /**
     * 发起请求
     *
     * @param requestUrl 请求地址
     * @param params     参数
     * @return
     */
    public static String post(String requestUrl, MultiValueMap<String, Object> params) {
        logger.info("请求: {}, 参数: {}", requestUrl, JSONObject.toJSON(params));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity request = new HttpEntity<>(params, headers);
        try {
            String result = restTemplate.postForObject(requestUrl, request, String.class);
            logger.info("返回结: {}", result);
            return result;
        } catch (Exception e) {
            logger.info("接口请求异常: {}", e);
            throw new BusinessException("接口请求异常");
        }
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        RequestUtil.restTemplate = restTemplate;
    }
}
